﻿using CIS.DB;
using CIS.Web.Common;
using CIS.Web.Models;
using CIS.Web.Properties;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.IO;
using System.Linq;
using System.Linq.Dynamic;
using System.Net.Mail;
using System.Threading.Tasks;
using System.Web.Mvc;

namespace CIS.Web.Controllers
{
	[RoutePrefix("ConferenceLocale")]
	public class ConferenceLocaleController : BaseDbController
	{
		private string _importMessage;

		[Route("Index/{ConferenceId}")]
		public async Task<ActionResult> Index(string conferenceId)
		{
			string controller = RouteData.Values["controller"].ToString();
			string actionName = RouteData.Values["action"].ToString();
			Utility.InsertLog(LoginUser, Request.Url.ToString(), controller, actionName, "Index", conferenceId);

			var conferenceMaster = await DbContext.ConferenceMaster.AsNoTracking()
					.FirstOrDefaultAsync(x => x.Status == ConstValues.Status.正常 &&
						x.ID == conferenceId);

			ViewBag.ConferenceId = conferenceId;
			ViewBag.ConferenceName = conferenceMaster.ConferenceName;
			ViewBag.ControllerName = Resources.ConferenceLocale;
			ViewBag.Language = conferenceMaster.IsInternational ? ConstValues.Language.En : ConstValues.Language.Cn;

			var model = new ConferenceLocaleModel();
			model.ConferenceId = conferenceId;
			model.IsBenifitParice = conferenceMaster.BenefitStartDate.Value <= DateTime.Now && conferenceMaster.BenefitEndDate.Value >= DateTime.Now ? true : false;
			LoginUser.ConferenceFunctionIdList = Utility.GetConferenceFunctionIdList(conferenceId);
			return View(model);
		}

		public async Task<JsonCamelCaseResult> GetData(int? page, int? rows, string sort, string order, string conferenceId, ConferenceLocaleModel model)
		{
			int take = rows ?? ConstValues.DefaultGridRows;
			int skip = ((page ?? 1) - 1) * take;

			var conferenceInfo = await DbContext.ConferenceMaster.AsNoTracking().FirstOrDefaultAsync(y => y.ID == conferenceId);
			var isInternational = conferenceInfo.IsInternational;

			var sql = from attendenceInfo in DbContext.ConferenceAttendenceInfo.AsNoTracking()
					.Where(x => x.ConferenceId == conferenceId)
				  join paymentType in DbContext.ConferencePaymentMaster.AsNoTracking()
				       on attendenceInfo.PaymentTypeId equals paymentType.ID into paytypes
				  from paytype in paytypes.DefaultIfEmpty()
				  join sysPaymentType in DbContext.SysPaymentMaster.AsNoTracking()
				       on paytype.PayId equals sysPaymentType.ID into sysPayTypes
				  from sysPayType in sysPayTypes.DefaultIfEmpty()
				  orderby attendenceInfo.Sort ascending, attendenceInfo.UpdateDate descending
				  select new
				  {
					  ID = attendenceInfo.ID,
					  FullName = attendenceInfo.FullName,
					  Affiliation = attendenceInfo.Affiliation,
					  Telephone = attendenceInfo.Telephone,
					  Mobile = attendenceInfo.Mobile,
					  Mail = attendenceInfo.Mail,
					  Sort = attendenceInfo.Sort,
					  HasArrived = attendenceInfo.HasArrived,
					  HasPaid = attendenceInfo.HasPaid,
					  HasPrinted = attendenceInfo.HasPrinted,
					  HasDinner = attendenceInfo.HasDinner,
					  HasInvoiced = attendenceInfo.HasInvoiced,
					  TotalFee = DateTime.Now >= conferenceInfo.BenefitStartDate &&
							DateTime.Now <= conferenceInfo.BenefitEndDate &&
							attendenceInfo.Discount.HasValue ? attendenceInfo.Discount : attendenceInfo.TotalFee,
					  ActuallyFee = attendenceInfo.ActuallyFee,
					  Currency = attendenceInfo.Currency,
					  PayTypeId = paytype.ID,
					  PayType = sysPayType.PaymentName,
					  PayTypeEn = sysPayType.PaymentNameEn,
					  Remark = attendenceInfo.Remark,
					  CreateDate = attendenceInfo.CreateDate,
					  Creator = attendenceInfo.Creator,
					  CreateIP = attendenceInfo.CreateIP,
					  //发票
					  InvoiceTitle = attendenceInfo.InvoiceTitle,
					  InvoiceNum = attendenceInfo.InvoiceNum,
					  Bank = attendenceInfo.Bank,
					  BankAccount = attendenceInfo.BankAccount,
					  AddressAndTel = attendenceInfo.AddressAndTel,
					  TaxNum = attendenceInfo.TaxNum,
					  InvoiceId = attendenceInfo.InvoiceId,
					  //参会身份
					  AttendenceIdentityId = attendenceInfo.AttendenceIdentityId,
					  UpdateDate = attendenceInfo.UpdateDate,
					  HasSendPaid = attendenceInfo.HasSendPaid,
					  IsRefund = attendenceInfo.IsRefund
				  };

			if (!string.IsNullOrWhiteSpace(model.selId))
			{
				var valueId = model.selId;
				sql = sql.Where(x => x.ID.ToString().Contains(valueId));
			}

			if (!string.IsNullOrWhiteSpace(model.selSearchId))
			{
				sql = sql.Where(x => x.Mobile.Contains(model.selSearchId) ||
						x.Telephone.Contains(model.selSearchId) ||
						x.FullName.Contains(model.selSearchId) ||
						x.Mail.Contains(model.selSearchId) ||
						x.Affiliation.Contains(model.selSearchId));
			}

			if (!string.IsNullOrWhiteSpace(model.selPaidType))
			{
				sql = sql.Where(x => x.PayTypeId == model.selPaidType);
			}

			if (!string.IsNullOrWhiteSpace(model.selPaidStatus))
			{
				if (model.selPaidStatus == ConstValues.PaidStatus.退款)
				{
					sql = sql.Where(x => x.IsRefund == true);
				}
				else if (model.selPaidStatus == ConstValues.PaidStatus.已缴费)
				{
					sql = sql.Where(x => x.HasPaid == true && x.IsRefund == false);
				}
				else
				{
					sql = sql.Where(x => x.HasPaid == false && x.IsRefund == false);
				}
			}

			if (model.selArriveStatus.HasValue)
			{
				sql = sql.Where(x => x.HasArrived == model.selArriveStatus);
			}

			if (model.selDinnerStatus.HasValue)
			{
				sql = sql.Where(x => x.HasDinner == model.selDinnerStatus);
			}

			if (model.selInvoiceStatus.HasValue)
			{
				sql = sql.Where(x => x.HasInvoiced == model.selInvoiceStatus);
			}

			int total = await sql.CountAsync();

			if (!string.IsNullOrEmpty(sort))
			{
				sql = sql.OrderBy(sort + ConstValues.chrSpace + order).Skip(skip).Take(take);
			}
			else
			{
				sql = sql.OrderBy(x => x.Sort).ThenByDescending(x => x.CreateDate).Skip(skip).Take(take);
			}

			var sqlResult = await sql.ToListAsync();

			var result = sqlResult.Select(x => new
			{
				ID = x.ID,
				FullName = x.FullName == null ? string.Empty : x.FullName,
				Affiliation = x.Affiliation,
				TotalFee = x.TotalFee == null ? x.Currency + ConstValues.paymentZero.ToString("N2") : x.Currency + x.TotalFee.Value.ToString("N2"),
				ActuallyFee = x.ActuallyFee == null ? x.Currency + ConstValues.paymentZero.ToString("N2") : x.Currency + x.ActuallyFee.Value.ToString("N2"),
				HasArrived = x.HasArrived ? Resources.IsArrived + "(" + (isInternational == true ? x.UpdateDate.Value.ToString("MM/dd/yyyy HH:mm") : x.UpdateDate.Value.ToString("yyyy-MM-dd HH:mm")) + ")" : Resources.IsNotArrived,
				HasPaid = x.IsRefund ? Resources.Refunded : x.HasPaid ? Resources.HasPaid : Resources.HasNotPaid,
				HasDinner = x.HasDinner ? Resources.Yes : Resources.No,
				HasInvoiced = x.HasInvoiced ? Resources.HasInvoiced : Resources.HasNotInvoiced,
				PayType = isInternational ? x.PayTypeEn : x.PayType,
				HasPrinted = x.HasPrinted ? Resources.CardHasPrint : Resources.CardHasNotPrint,
				HasSendPaid = x.HasSendPaid ? Resources.HasSend : Resources.HasNotSend,
				Currency = x.Currency,
				//发票
				InvoiceTitle = x.InvoiceTitle,
				InvoiceNum = x.InvoiceNum,
				Bank = x.Bank,
				BankAccount = x.BankAccount,
				AddressAndTel = x.AddressAndTel,
				TaxNum = x.TaxNum,
				InvoiceDetail = DbContext.ConferenceInvoiceMaster.AsNoTracking().FirstOrDefault(y => y.ID == x.InvoiceId)?.InvoiceDetail,
				//参会身份
				AttendenceIdentityId = DbContext.AttendenceIdentityMaster.AsNoTracking().FirstOrDefault(y => y.ID == x.AttendenceIdentityId)?.IdentityName,
				Remark = x.Remark,
				Sort = x.Sort,
				Creator = x.Creator,
				CreateIP = x.CreateIP,
				CreateDate = Request.Cookies["_culture"].Value == ConstValues.Language.Cn ?
							x.CreateDate.Value.ToString("yyyy-MM-dd") :
							x.CreateDate.Value.ToString("MM/dd/yyyy")
			});

			return JsonCamelCase(new
			{
				Total = total,
				Rows = result,
			},
			JsonRequestBehavior.AllowGet);
		}

		public async Task<JsonCamelCaseResult> GetScanData(string id)
		{
			var sqlResult = await DbContext.ConferenceAttendenceInfo.AsNoTracking()
					.FirstOrDefaultAsync(x => x.ID == id);

			if (sqlResult == null)
			{
				return JsonCamelCase(Utility.CreateFailJsonResult(Resources.MsgRecordNotExist),
						JsonRequestBehavior.AllowGet);
			}

			var conferenceMaster = await DbContext.ConferenceMaster.AsNoTracking().FirstOrDefaultAsync(y => y.ID == sqlResult.ConferenceId);

			var result = new
			{
				FullName = sqlResult.FullName,
				PaymentShouldPay = DateTime.Now >= conferenceMaster.BenefitStartDate &&
					DateTime.Now <= conferenceMaster.BenefitEndDate &&
					sqlResult.Discount.HasValue ? sqlResult.Discount.Value.ToString("N2") : sqlResult.TotalFee.Value.ToString("N2"),
				PaymentHasPay = sqlResult.ActuallyFee == null ? string.Empty : sqlResult.ActuallyFee.Value.ToString("N2"),
				ArriveStatus = sqlResult.HasArrived ? ConstValues.GenericSelectionType.有 : ConstValues.GenericSelectionType.无,
				PayStatus = sqlResult.IsRefund ? ConstValues.PaidStatus.退款 : sqlResult.HasPaid ? ConstValues.PaidStatus.已缴费 : ConstValues.PaidStatus.未缴费,
				DinnerStatus = sqlResult.HasDinner ? ConstValues.GenericSelectionType.有 : ConstValues.GenericSelectionType.无,
				PaymentType = sqlResult.PaymentTypeId,
				AttendCardPrint = sqlResult.HasPrinted ? ConstValues.GenericSelectionType.有 : ConstValues.GenericSelectionType.无,
				InvoiceNum = sqlResult.InvoiceNum,
				Remark = sqlResult.Remark
			};

			return JsonCamelCase(Utility.CreateSuccessJsonResult(ConstValues.AjaxSuccessResult, result),
					JsonRequestBehavior.AllowGet);
		}

		public async Task<JsonCamelCaseResult> GetLocaleDataById(string id)
		{
			var sqlResult = await DbContext.ConferenceAttendenceInfo.AsNoTracking()
					.FirstOrDefaultAsync(x => x.ID == id);

			if (sqlResult == null)
			{
				return JsonCamelCase(Utility.CreateFailJsonResult(Resources.MsgRecordNotExist),
						JsonRequestBehavior.AllowGet);
			}

			var conferenceMaster = await DbContext.ConferenceMaster.AsNoTracking().FirstOrDefaultAsync(y => y.ID == sqlResult.ConferenceId);

			var result = new
			{
				FullName = sqlResult.FullName,
				PaymentShouldPay = DateTime.Now >= conferenceMaster.BenefitStartDate &&
					DateTime.Now <= conferenceMaster.BenefitEndDate &&
					sqlResult.Discount.HasValue ? sqlResult.Discount.Value.ToString("N2") : sqlResult.TotalFee.Value.ToString("N2"),
				PaymentHasPay = sqlResult.ActuallyFee == null ? string.Empty : sqlResult.ActuallyFee.Value.ToString("N2"),
				ArriveStatus = sqlResult.HasArrived ? ConstValues.GenericSelectionType.有 : ConstValues.GenericSelectionType.无,
				PayStatus = sqlResult.IsRefund ? ConstValues.PaidStatus.退款 : sqlResult.HasPaid ? ConstValues.PaidStatus.已缴费 : ConstValues.PaidStatus.未缴费,
				DinnerStatus = sqlResult.HasDinner ? ConstValues.GenericSelectionType.有 : ConstValues.GenericSelectionType.无,
				PaymentType = sqlResult.PaymentTypeId,
				AttendCardPrint = sqlResult.HasPrinted ? ConstValues.GenericSelectionType.有 : ConstValues.GenericSelectionType.无,
				InvoiceNum = sqlResult.InvoiceNum,
				Remark = sqlResult.Remark
			};

			return JsonCamelCase(Utility.CreateSuccessJsonResult(ConstValues.AjaxSuccessResult, result),
					JsonRequestBehavior.AllowGet);
		}

		[HttpPost]
		[ValidateAntiForgeryToken]
		[Route("SaveLocaleManage/{ConferenceId}")]
		public async Task<JsonResult> SaveLocaleManage(ConferenceLocaleModel model)
		{
			string controller = RouteData.Values["controller"].ToString();
			string actionName = RouteData.Values["action"].ToString();
			Utility.InsertLog(LoginUser, Request.Url.ToString(), controller, actionName, "Index", model.ConferenceId);

			var result = await DbContext.ConferenceAttendenceInfo
					.FirstOrDefaultAsync(x => x.ID == model.Id);

			if (result == null)
			{
				return JsonCamelCase(Utility.CreateFailJsonResult(Resources.MsgRecordNotExist),
						JsonRequestBehavior.AllowGet);
			}

			if ((!result.IsRefund && model.PayStatus == ConstValues.PaidStatus.退款) ||
				(!result.HasPaid && model.PayStatus == ConstValues.PaidStatus.已缴费) ||
				(result.HasPaid && model.PayStatus == ConstValues.PaidStatus.未缴费))
			{
				var conferencePayStatusInfo = new ConferencePayStatusInfo
				{
					ID = Utility.GetTableId(ConstValues.TableName.ConferencePayStatusInfo),
					ConferenceId = model.ConferenceId,
					UserName = result.Creator,
					AttendenceId = result.ID,
					Fee = Utility.ObjectToDouble(model.ActuallyFee),
					Currency = result.Currency,
					FeeStatus = model.PayStatus,
					Creator = LoginUser.UserName,
					CreateDate = DateTime.Now,
					CreateIP = LoginUser.IP
				};
				DbContext.ConferencePayStatusInfo.Add(conferencePayStatusInfo);
			}

			result.ActuallyFee = Utility.ObjectToDouble(model.ActuallyFee);
			result.PaymentTypeId = model.PaymentType;

			switch (model.PayStatus)
			{
				case ConstValues.PaidStatus.退款:
					result.IsRefund = true;
					break;
				case ConstValues.PaidStatus.已缴费:
					result.IsRefund = false;
					result.HasPaid = true;
					break;
				case ConstValues.PaidStatus.未缴费:
					result.IsRefund = false;
					result.HasPaid = false;
					break;
			}
			result.HasArrived = model.ArriveStatus;
			result.HasDinner = model.DinnerStatus;
			result.HasPrinted = model.AttendCardPrint;
			if (model.ArriveStatus == true)
			{
				result.AttendDate = DateTime.Now;
			}

			result.InvoiceNum = model.InvoiceNum;
			if (!string.IsNullOrEmpty(model.InvoiceNum))
			{
				result.HasInvoiced = true;
			}
			result.Remark = model.Remark;

			result.Updater = LoginUser.UserName;
			result.UpdateIP = LoginUser.IP;
			result.UpdateDate = DateTime.Now;

			await DbContext.SaveChangesAsync();

			return JsonCamelCase(Utility.CreateSuccessJsonResult(Resources.SuccessSubmit),
					JsonRequestBehavior.AllowGet);
		}

		[HttpPost]
		[ValidateAntiForgeryToken]
		[Route("SaveLocaleManageSendMail/{ConferenceId}")]
		public async Task<JsonResult> SaveLocaleManageSendMail(ConferenceLocaleModel model)
		{
			string controller = RouteData.Values["controller"].ToString();
			string actionName = RouteData.Values["action"].ToString();
			Utility.InsertLog(LoginUser, Request.Url.ToString(), controller, actionName, "Index", model.ConferenceId);

			var result = await DbContext.ConferenceAttendenceInfo
					.FirstOrDefaultAsync(x => x.ID == model.Id);

			if (result == null)
			{
				return JsonCamelCase(Utility.CreateFailJsonResult(Resources.MsgRecordNotExist),
						JsonRequestBehavior.AllowGet);
			}

			if ((!result.IsRefund && model.PayStatus == ConstValues.PaidStatus.退款) ||
				(!result.HasPaid && model.PayStatus == ConstValues.PaidStatus.已缴费) ||
				(result.HasPaid && model.PayStatus == ConstValues.PaidStatus.未缴费))
			{
				var conferencePayStatusInfo = new ConferencePayStatusInfo
				{
					ID = Utility.GetTableId(ConstValues.TableName.ConferencePayStatusInfo),
					ConferenceId = model.ConferenceId,
					UserName = result.Creator,
					AttendenceId = result.ID,
					Fee = Utility.ObjectToDouble(model.ActuallyFee),
					Currency = result.Currency,
					FeeStatus = model.PayStatus,
					Creator = LoginUser.UserName,
					CreateDate = DateTime.Now,
					CreateIP = LoginUser.IP
				};
				DbContext.ConferencePayStatusInfo.Add(conferencePayStatusInfo);
			}

			result.ActuallyFee = Utility.ObjectToDouble(model.ActuallyFee);
			result.PaymentTypeId = model.PaymentType;
			switch (model.PayStatus)
			{
				case ConstValues.PaidStatus.退款:
					result.IsRefund = true;
					break;
				case ConstValues.PaidStatus.已缴费:
					result.IsRefund = false;
					result.HasPaid = true;
					break;
				case ConstValues.PaidStatus.未缴费:
					result.IsRefund = false;
					result.HasPaid = false;
					break;
			}
			result.HasArrived = model.ArriveStatus;
			result.HasDinner = model.DinnerStatus;
			result.HasPrinted = model.AttendCardPrint;
			if (model.ArriveStatus == true)
			{
				result.AttendDate = DateTime.Now;
			}

			result.InvoiceNum = model.InvoiceNum;
			if (!string.IsNullOrEmpty(model.InvoiceNum))
			{
				result.HasInvoiced = true;
			}
			result.Remark = model.Remark;

			result.Updater = LoginUser.UserName;
			result.UpdateIP = LoginUser.IP;
			result.UpdateDate = DateTime.Now;

			#region SendMail
			var conferenceMailServerMaster = await DbContext.ConferenceMailServerMaster.AsNoTracking()
					.FirstOrDefaultAsync(x => x.Status == ConstValues.Status.正常 &&
						x.MailType == ConstValues.MailType.注册服务邮箱 &&
						x.ConferenceId == result.ConferenceId);

			if (conferenceMailServerMaster == null)
			{
				conferenceMailServerMaster = await DbContext.ConferenceMailServerMaster.AsNoTracking()
						.FirstOrDefaultAsync(x => x.Status == ConstValues.Status.正常 &&
							x.MailType == ConstValues.MailType.会议邮箱 &&
							x.ConferenceId == result.ConferenceId);
			}

			if (conferenceMailServerMaster != null)
			{
				var conferenceMaster = await DbContext.ConferenceMaster.AsNoTracking()
						.FirstOrDefaultAsync(x => x.ID == model.ConferenceId);
				var conferencePayment = await DbContext.ConferencePaymentMaster.AsNoTracking()
						.FirstOrDefaultAsync(x => x.ID == result.PaymentTypeId);
				var sysPayment = await DbContext.SysPaymentMaster.AsNoTracking()
						.FirstOrDefaultAsync(x => x.ID == conferencePayment.PayId);

				MailSender sender = new MailSender(conferenceMailServerMaster.MailServer);
				MailAddress from = new MailAddress(conferenceMailServerMaster.Mail);
				MailAddress to = new MailAddress(result.Mail);

				MailMessage message = Utility.GetMailContent(new MailModel
				{
					MailRemark = ConstValues.MailSubject.缴费成功,
					Language = conferenceMaster.IsInternational ? ConstValues.Language.En : ConstValues.Language.Cn,
					UserName = result.FullName,
					ConferenceId = conferenceMaster.ID,
					ConferenceName = conferenceMaster.ConferenceName,
					ConferenceNickName = conferenceMaster.ConferenceNickName,
					ConferenceUrl = !string.IsNullOrEmpty(conferenceMaster.HomePageUrl) ? conferenceMaster.HomePageUrl :
						ConstValues.SystemWeb + "/MeetingMain/Index/" + conferenceMaster.ConferenceNickName,
					Currency = result.Currency,
					TotalFee = result.ActuallyFee.Value.ToString("N2"),
					PaymentType = conferenceMaster.IsInternational ? sysPayment.PaymentNameEn : sysPayment.PaymentName,
					PaidStatus = Resources.HasPaid,
					PayList = Utility.GetPayDetailList(model.Id, conferenceMaster.ID, conferenceMaster.BenefitStartDate, conferenceMaster.BenefitEndDate)
				});
				message.To.Add(to);

				if (!string.IsNullOrWhiteSpace(conferenceMailServerMaster.CcMail))
				{
					foreach (string cc in conferenceMailServerMaster.CcMail.Split(ConstValues.chrSemicolon))
					{
						if (!string.IsNullOrWhiteSpace(cc) && cc.Contains(ConstValues.chrAt))
						{
							message.Bcc.Add(new MailAddress(cc.Trim()));
						}
					}
				}

				var strMsg = string.Empty;
				var mailTask = Task.Run(() =>
				{
					strMsg = sender.SendMail(from, message, conferenceMailServerMaster.Password);
				});
				if (string.IsNullOrEmpty(strMsg))
				{
					result.HasSendPaid = true;
				}
			}
			#endregion

			await DbContext.SaveChangesAsync();

			return JsonCamelCase(Utility.CreateSuccessJsonResult(Resources.SuccessSubmit),
					JsonRequestBehavior.AllowGet);
		}

		public async Task<JsonCamelCaseResult> GetInvoiceManageById(string id)
		{
			var sqlResult = await DbContext.ConferenceAttendenceInfo.AsNoTracking()
					.FirstOrDefaultAsync(x => x.ID == id);

			if (sqlResult == null)
			{
				return JsonCamelCase(Utility.CreateFailJsonResult(Resources.MsgRecordNotExist),
						JsonRequestBehavior.AllowGet);
			}

			var result = new
			{
				HasInvoiced = sqlResult.HasInvoiced ? true : !string.IsNullOrEmpty(sqlResult.InvoiceNum) ? true : false,
				InvoiceTitle = sqlResult.InvoiceTitle == null ? string.Empty : sqlResult.InvoiceTitle,
				TaxNum = sqlResult.TaxNum == null ? string.Empty : sqlResult.TaxNum,
				AddressAndTel = sqlResult.AddressAndTel == null ? string.Empty : sqlResult.AddressAndTel,
				Bank = sqlResult.Bank == null ? string.Empty : sqlResult.Bank,
				BankAccount = sqlResult.BankAccount == null ? string.Empty : sqlResult.BankAccount,
				InvoiceType = sqlResult.InvoiceType == null ? string.Empty : sqlResult.InvoiceType,
				InvoiceClass = sqlResult.InvoiceClass == null ? string.Empty : sqlResult.InvoiceClass,
				InvoiceDate = sqlResult.InvoiceDate,
				InvoiceCode = sqlResult.InvoiceCode == null ? string.Empty : sqlResult.InvoiceCode,
				InvoiceNum = sqlResult.InvoiceNum == null ? string.Empty : sqlResult.InvoiceNum,
				InvoiceAmount = sqlResult.InvoiceAmount,
				InvoiceAddress = string.IsNullOrEmpty(sqlResult.InvoiceAddress) ? sqlResult.Address : sqlResult.InvoiceAddress,
				InvoiceReceive = string.IsNullOrEmpty(sqlResult.InvoiceReceive) ? sqlResult.FullName : sqlResult.InvoiceReceive,
				InvoiceTel = string.IsNullOrEmpty(sqlResult.InvoiceTel) ? sqlResult.Mobile : sqlResult.InvoiceTel,
				InvoiceExpress = sqlResult.InvoiceExpress == null ? string.Empty : sqlResult.InvoiceExpress,
				InvoiceMail = string.IsNullOrEmpty(sqlResult.InvoiceMail) ? sqlResult.Mail : sqlResult.InvoiceMail,
			};

			return JsonCamelCase(Utility.CreateSuccessJsonResult(ConstValues.AjaxSuccessResult, result),
					JsonRequestBehavior.AllowGet);
		}

		[HttpPost]
		[ValidateAntiForgeryToken]
		[Route("SaveInvoiceInfo/{ConferenceId}")]
		public async Task<JsonResult> SaveInvoiceInfo(ConferenceLocaleModel model)
		{
			string controller = RouteData.Values["controller"].ToString();
			string actionName = RouteData.Values["action"].ToString();
			Utility.InsertLog(LoginUser, Request.Url.ToString(), controller, actionName, "Index", model.ConferenceId);

			var result = await DbContext.ConferenceAttendenceInfo
					.FirstOrDefaultAsync(x => x.ID == model.Id);

			if (result == null)
			{
				return JsonCamelCase(Utility.CreateFailJsonResult(Resources.MsgRecordNotExist),
						JsonRequestBehavior.AllowGet);
			}

			result.HasInvoiced = model.HasInvoiced ? true : !string.IsNullOrEmpty(model.InvoiceNum) ? true : false;
			result.InvoiceTitle = model.InvoiceTitle;
			result.TaxNum = model.TaxNum;
			result.AddressAndTel = model.AddressAndTel;
			result.Bank = model.Bank;
			result.BankAccount = model.BankAccount;
			result.InvoiceType = model.InvoiceType;
			result.InvoiceClass = model.InvoiceClass;
			result.InvoiceDate = model.InvoiceDate;
			result.InvoiceCode = model.InvoiceCode;
			result.InvoiceNum = model.InvoiceNum;
			result.InvoiceAmount = model.InvoiceAmount;
			result.InvoiceAddress = model.InvoiceAddress;
			result.InvoiceReceive = model.InvoiceReceive;
			result.InvoiceTel = model.InvoiceTel;
			result.InvoiceExpress = model.InvoiceExpress;
			result.InvoiceMail = model.InvoiceMail;

			result.Updater = LoginUser.UserName;
			result.UpdateIP = LoginUser.IP;
			result.UpdateDate = DateTime.Now;

			await DbContext.SaveChangesAsync();

			return JsonCamelCase(Utility.CreateSuccessJsonResult(Resources.SuccessSubmit),
					JsonRequestBehavior.AllowGet);
		}

		public async Task<JsonCamelCaseResult> GetPaymentInfoData(string id)
		{
			var sql = from paymentInfo in DbContext.ProfilePaymentInfo.AsNoTracking()
					.Where(x => x.AttendenceId == id)
				  join attInfo in DbContext.ConferenceAttendenceInfo.AsNoTracking()
					on paymentInfo.AttendenceId equals attInfo.ID
				  join conferenceMaster in DbContext.ConferenceMaster.AsNoTracking()
					on attInfo.ConferenceId equals conferenceMaster.ID
				  orderby paymentInfo.FeeType
				  select new ProfilePayInfoModel
				  {
					  FeeType = paymentInfo.FeeType,
					  FeeId = paymentInfo.FeeId,
					  FeeName = string.Empty,
					  Count = paymentInfo.Count,
					  Currency = paymentInfo.Currency,
					  Fee = paymentInfo.Fee,
					  Discount = paymentInfo.Discount,
					  BenefitEndDate = conferenceMaster.BenefitEndDate,
					  BenefitStartDate = conferenceMaster.BenefitStartDate,
					  ConferenceId = conferenceMaster.ID,
					  DisplayName = ""
				  };

			int total = await sql.CountAsync();
			var sqlResult = await sql.ToListAsync();

			double? conferenceFee = 0.00;
			double? eventFee = 0.00;
			string totalCurrency = "";
			sqlResult.ForEach(x =>
			{
				if (x.FeeType == ConstValues.FeeType.餐费)
				{
					x.DisplayName = DbContext.ConferenceAttendenceForm.AsNoTracking().FirstOrDefault(y => y.ConferenceId == x.ConferenceId && y.Key == "Meal")?.DisplayName;
					double? Fee = x.BenefitStartDate < DateTime.Now && DateTime.Now < x.BenefitEndDate ? x.Discount : x.Fee;
					conferenceFee += Fee;
					x.FeeName = DbContext.FeeMealMaster.AsNoTracking().FirstOrDefault(y => y.ID == x.FeeId).FeeName;
					totalCurrency = x.Currency;
				}
				else if (x.FeeType == ConstValues.FeeType.参会费)
				{
					x.DisplayName = DbContext.ConferenceAttendenceForm.AsNoTracking().FirstOrDefault(y => y.ConferenceId == x.ConferenceId && y.Key == "Attendence")?.DisplayName;
					double? Fee = x.BenefitStartDate < DateTime.Now && DateTime.Now < x.BenefitEndDate ? x.Discount : x.Fee;
					conferenceFee += Fee;
					x.FeeName = DbContext.FeeAttendenceMaster.AsNoTracking().FirstOrDefault(y => y.ID == x.FeeId).RegisterType;
					totalCurrency = x.Currency;
				}
				else if (x.FeeType == ConstValues.FeeType.版面费)
				{
					x.DisplayName = DbContext.ConferenceAttendenceForm.AsNoTracking().FirstOrDefault(y => y.ConferenceId == x.ConferenceId && y.Key == "Page")?.DisplayName;
					double? Fee = x.BenefitStartDate < DateTime.Now && DateTime.Now < x.BenefitEndDate ? x.Discount : x.Fee;
					conferenceFee += Fee;
					x.FeeName = DbContext.FeePageMaster.AsNoTracking().FirstOrDefault(y => y.ID == x.FeeId).FeeName;
					totalCurrency = x.Currency;
				}
				else if (x.FeeType == ConstValues.FeeType.其他费用)
				{
					x.DisplayName = DbContext.ConferenceAttendenceForm.AsNoTracking().FirstOrDefault(y => y.ConferenceId == x.ConferenceId && y.Key == "Other")?.DisplayName;
					double? Fee = x.BenefitStartDate < DateTime.Now && DateTime.Now < x.BenefitEndDate ? x.Discount : x.Fee;
					conferenceFee += Fee;
					x.FeeName = DbContext.FeeOtherMaster.AsNoTracking().FirstOrDefault(y => y.ID == x.FeeId).FeeName;
					totalCurrency = x.Currency;
				}
				else if (x.FeeType == ConstValues.FeeType.同期活动费)
				{
					x.DisplayName = DbContext.ConferenceAttendenceForm.AsNoTracking().FirstOrDefault(y => y.ConferenceId == x.ConferenceId && y.Key == "ConcurrentEvent")?.DisplayName;
					var ConcurrentEventId = DbContext.FeeConcurrentEventMaster.AsNoTracking().FirstOrDefault(y => y.ID == x.FeeId)?.ConcurrentEventId;
					x.FeeName = DbContext.ConcurrentEventMaster.AsNoTracking().FirstOrDefault(y => y.ID == ConcurrentEventId)?.EventName;
					double? Fee = x.BenefitStartDate < DateTime.Now && DateTime.Now < x.BenefitEndDate ? x.Discount : x.Fee;
					eventFee += Fee;
					totalCurrency = x.Currency;
				}
			});

			var result = sqlResult.Select(x => new
			{
				FeeType = x.DisplayName,
				FeeName = x.FeeName,
				Count = x.Count,
				Currency = x.Currency,
				Fee = x.BenefitStartDate < DateTime.Now && DateTime.Now < x.BenefitEndDate ? x.Discount.Value.ToString("N2") : x.Fee.Value.ToString("N2"),
				Discount = x.Discount.Value.ToString("N2")
			});

			return JsonCamelCase(new
			{
				Total = total,
				Rows = result,
			},
			JsonRequestBehavior.AllowGet);
		}

		[Route("GetPersonalData/{id}")]
		public async Task<JsonCamelCaseResult> GetPersonalData(string id)
		{
			var personal = await DbContext.ConferenceAttendenceInfo.AsNoTracking().FirstOrDefaultAsync(x => x.ID == id);
			if (personal != null)
			{
				return JsonCamelCase(Utility.CreateFailJsonResult(Resources.MsgRecordNotExist),
						JsonRequestBehavior.AllowGet);
			}

			var conferenceMaster = await DbContext.ConferenceMaster.AsNoTracking().FirstOrDefaultAsync(x => x.ID == personal.ConferenceId);

			var isBenefit = false;
			if (DateTime.Now >= conferenceMaster.BenefitStartDate && DateTime.Now <= conferenceMaster.BenefitEndDate)
			{
				isBenefit = true;
			}
			var payTypeId = DbContext.ConferencePaymentMaster.AsNoTracking().FirstOrDefault(x => x.ID == personal.PaymentTypeId)?.PayId;
			var essayList = await DbContext.ConferenceContributeInfo.AsNoTracking()
					.Where(x => personal.EssayId.Contains(x.ID.ToString()))
					.Select(x => x.EssayTitle)
					.ToListAsync();

			var essayArray = essayList.ToArray();
			var essay = string.Join(ConstValues.strSemicolon, essayArray);
			var result = new
			{
				fullname = personal.FullName,
				affiliation = personal.Affiliation,
				mail = personal.Mail,
				tele = personal.Telephone,
				country = conferenceMaster.IsInternational ?
						DbContext.LocationMaster.AsNoTracking().FirstOrDefault(x => x.ID == personal.Country)?.NameEn :
						DbContext.LocationMaster.AsNoTracking().FirstOrDefault(x => x.ID == personal.Country)?.Name,
				essay = essay,
				address = personal.Address,
				zipCode = personal.ZipCode,
				fee = personal.Currency + ConstValues.strSpace + (isBenefit ? personal.Discount : personal.TotalFee).Value.ToString("N2"),
				payType = conferenceMaster.IsInternational ?
						DbContext.SysPaymentMaster.AsNoTracking().FirstOrDefault(x => x.ID == payTypeId)?.PaymentNameEn :
						DbContext.SysPaymentMaster.AsNoTracking().FirstOrDefault(x => x.ID == payTypeId)?.PaymentName,
				invoiceTitle = personal.InvoiceTitle,
				hotelId = DbContext.HotelMaster.AsNoTracking().FirstOrDefault(x => x.ID == personal.HotelId)?.HotelName,
				roomTypeId = DbContext.RoomMaster.AsNoTracking().FirstOrDefault(x => x.ID == personal.RoomTypeId)?.RoomType,
				arrivalDate = personal.ArrivalDate.HasValue ?
						(Request.Cookies["_culture"].Value == ConstValues.Language.Cn ?
						personal.ArrivalDate.Value.ToString("yyyy-MM-dd") :
						personal.ArrivalDate.Value.ToString("MM/dd/yyyy")) : null,
				creator = personal.Creator,
				departuralDate = personal.DeparturalDate.HasValue ?
						(Request.Cookies["_culture"].Value == ConstValues.Language.Cn ?
						personal.DeparturalDate.Value.ToString("yyyy-MM-dd") :
						personal.DeparturalDate.Value.ToString("MM/dd/yyyy")) : null,
				Id = personal.ID,
				arrivalFlight = personal.ArrivalFlight,
				departuralFlight = personal.DeparturalFlight,
				remark = personal.Remark,
				createDate = personal.CreateDate.HasValue ?
						(Request.Cookies["_culture"].Value == ConstValues.Language.Cn ?
						personal.CreateDate.Value.ToString("yyyy-MM-dd") :
						personal.CreateDate.Value.ToString("MM/dd/yyyy")) : null,
				hotelRemark = personal.HotelRemark,
				attendenceIdentity = personal.AttendenceIdentityId
			};

			return JsonCamelCase(Utility.CreateSuccessJsonResult(string.Empty, result),
					JsonRequestBehavior.AllowGet);
		}

		public async Task<ActionResult> PrintView(string id)
		{
			var attendInfo = await DbContext.ConferenceAttendenceInfo
					.FirstOrDefaultAsync(x => x.ID == id);
			var conference = await DbContext.ConferenceMaster.AsNoTracking()
					.FirstOrDefaultAsync(x => x.ID == attendInfo.ConferenceId);
			var location = await DbContext.LocationMaster.AsNoTracking()
					.FirstOrDefaultAsync(x => x.ID == attendInfo.Country);
			var setting = await DbContext.ConferencePrintMaster.AsNoTracking()
					.FirstOrDefaultAsync(x => x.ConferenceId == attendInfo.ConferenceId);

			if (string.IsNullOrEmpty(attendInfo.BarCode))
			{
				attendInfo.BarCode = Utility.CreateBarCode(id,
					Server.MapPath(Path.Combine(ConstValues.BarCodeImg, conference.ConferenceNickName)),
					Path.Combine(ConstValues.BarCodeImg, conference.ConferenceNickName));
				await DbContext.SaveChangesAsync();
			}

			var model = new ConferenceLocaleModel()
			{
				AttendId = id,
				FullName = attendInfo.FullName,
				Affiliation = attendInfo.Affiliation,
				ConferenceId = attendInfo.ConferenceId,
				Country = Request.Cookies["_culture"].Value == ConstValues.Language.Cn ? location?.Name : location?.NameEn,

				IsShowName = setting != null && !setting.IsShowName ? 0 : 1,
				NameSize = setting != null ? setting.NameSize : 30,
				IsNameBold = setting != null && setting.IsNameBold ? 1 : 0,
				IsNameOblique = setting != null && setting.IsNameOblique ? 1 : 0,
				NameLeft = setting != null ? setting.NameLeft : 0,
				NameTop = setting != null ? setting.NameTop : 0,

				IsShowAffiliation = setting != null && !setting.IsShowAffiliation ? 0 : 1,
				AffiliationSize = setting != null ? setting.AffiliationSize : 16,
				IsAffiliationBold = setting != null && setting.IsAffiliationBold ? 1 : 0,
				IsAffiliationOblique = setting != null && setting.IsAffiliationOblique ? 1 : 0,
				AffiliationLeft = setting != null ? setting.AffiliationLeft : 0,
				AffiliationTop = setting != null ? setting.AffiliationTop : 0,

				IsShowCountry = setting != null && setting.IsShowCountry ? 1 : 0,
				CountrySize = setting != null ? setting.CountrySize : 24,
				IsCountryBold = setting != null && setting.IsCountryBold ? 1 : 0,
				IsCountryOblique = setting != null && setting.IsCountryOblique ? 1 : 0,
				CountryLeft = setting != null ? setting.CountryLeft : 0,
				CountryTop = setting != null ? setting.CountryTop : 0,

				IsShowBarCode = setting != null && setting.IsShowBarCode ? 1 : 0,
				BarCodeSize = setting != null ? setting.BarCodeSize : 140,
				BarCodeLeft = setting != null ? setting.BarCodeLeft : 0,
				BarCodeTop = setting != null ? setting.BarCodeTop : 20,
				IsShowBackground = setting != null && setting.IsShowBackground ? 1 : 0,
				PicForBackgroundPath = setting != null ? setting.PicForBackground : string.Empty
			};

			return View(model);
		}

		public async Task<ActionResult> ProfilePrintView(string id)
		{
			var model = new ConferenceLocaleModel();

			var personal = await DbContext.ConferenceAttendenceInfo.AsNoTracking().FirstOrDefaultAsync(x => x.ID == id);
			var conferenceMaster = await DbContext.ConferenceMaster.AsNoTracking().FirstOrDefaultAsync(x => x.ID == personal.ConferenceId);

			string controller = RouteData.Values["controller"].ToString();
			string actionName = RouteData.Values["action"].ToString();
			Utility.InsertLog(LoginUser, Request.Url.ToString(), controller, actionName, "Index", conferenceMaster.ID);


			var isBenefit = false;
			if (DateTime.Now >= conferenceMaster.BenefitStartDate && DateTime.Now <= conferenceMaster.BenefitEndDate)
			{
				isBenefit = true;
			}
			var payTypeId = DbContext.ConferencePaymentMaster.AsNoTracking().FirstOrDefault(x => x.ID == personal.PaymentTypeId)?.PayId;

			//查询论文编号
			var essayList = await DbContext.ConferenceContributeInfo.AsNoTracking()
					.Where(x => personal.EssayId.Contains(x.ID.ToString()))
					//.Select(x => x.EssayTitle)
					.ToListAsync();
			List<string> strList = new List<string>();
			essayList.ForEach(x =>
			{
				var reportType = DbContext.ReportMaster.AsNoTracking().FirstOrDefault(y => y.ID == x.ReportId)?.ReportType;
				var rid = x.ID;
				var str = "";
				str += rid + ConstValues.strSpace + ConstValues.strLeftBracket + reportType + ConstValues.strRightBracket;
				strList.Add(str);
			});

			var essayArray = strList.ToArray();
			var essay = string.Join(ConstValues.chrSpace + ConstValues.strSemicolon + ConstValues.chrSpace, essayArray);

			//查询报告id
			var reportId = "";
			var reportList = await DbContext.ScheduleInfo.AsNoTracking().Where(x => personal.EssayId.Contains(x.ID.ToString())).ToListAsync();
			reportList.ForEach(x =>
			{
				if (reportId == "")
				{
					reportId += x.ID;
				}
				else
				{
					reportId += ConstValues.chrSpace + ConstValues.chrComma + ConstValues.chrSpace + x.ID;
				}
			});

			//查询费用明细
			var sql = from paymentInfo in DbContext.ProfilePaymentInfo.AsNoTracking()
				.Where(x => x.AttendenceId == id)
				  join attInfo in DbContext.ConferenceAttendenceInfo.AsNoTracking()
					  on paymentInfo.AttendenceId equals attInfo.ID
				  join conferenceMaster2 in DbContext.ConferenceMaster.AsNoTracking()
					  on attInfo.ConferenceId equals conferenceMaster2.ID
				  select new ProfilePayInfoModel
				  {
					  FeeType = paymentInfo.FeeType,
					  FeeId = paymentInfo.FeeId,
					  FeeName = string.Empty,
					  Count = paymentInfo.Count,
					  Currency = paymentInfo.Currency,
					  Fee = paymentInfo.Fee,
					  Discount = paymentInfo.Discount,
					  BenefitEndDate = conferenceMaster2.BenefitEndDate,
					  BenefitStartDate = conferenceMaster2.BenefitStartDate
				  };
			var sqlResult = await sql.ToListAsync();
			sqlResult.ForEach(x =>
			{
				if (x.FeeType == ConstValues.FeeType.餐费)
				{
					x.FeeType = Resources.FeeMeal;

					x.FeeName = DbContext.FeeMealMaster.AsNoTracking().FirstOrDefault(y => y.ID == x.FeeId).FeeName;
				}
				else if (x.FeeType == ConstValues.FeeType.参会费)
				{
					x.FeeType = Resources.FeeAttend;

					x.FeeName = DbContext.FeeAttendenceMaster.AsNoTracking().FirstOrDefault(y => y.ID == x.FeeId).RegisterType;
				}
				else if (x.FeeType == ConstValues.FeeType.版面费)
				{
					x.FeeType = Resources.FeePage;

					x.FeeName = DbContext.FeePageMaster.AsNoTracking().FirstOrDefault(y => y.ID == x.FeeId).FeeName;
				}
				else if (x.FeeType == ConstValues.FeeType.其他费用)
				{
					x.FeeType = Resources.FeeOther;

					x.FeeName = DbContext.FeeOtherMaster.AsNoTracking().FirstOrDefault(y => y.ID == x.FeeId).FeeName;
				}
				else if (x.FeeType == ConstValues.FeeType.同期活动费)
				{
					x.FeeType = Resources.ConferenceFeeEvent;
					var ConcurrentEventId = DbContext.FeeConcurrentEventMaster.AsNoTracking().FirstOrDefault(y => y.ID == x.FeeId)?.ConcurrentEventId;
					x.FeeName = DbContext.ConcurrentEventMaster.AsNoTracking().FirstOrDefault(y => y.ID == ConcurrentEventId)?.EventName;
				}
			});
			List<string> feeDetailList = new List<string>();
			sqlResult.ForEach(x =>
			{
				var detailStr = "";
				detailStr += x.FeeType;
				detailStr += ConstValues.strSpace;
				detailStr += x.FeeName;
				detailStr += ConstValues.strSpace;
				detailStr += x.Currency;
				detailStr += ConstValues.chrSpace;
				if (isBenefit)
				{
					detailStr += x.Discount;
				}
				else
				{
					detailStr += x.Fee;
				}
				feeDetailList.Add(detailStr);
			});
			var feeDetail = string.Join("\\n", feeDetailList);

			//查询支付时间
			var paymentRecord = await DbContext.ProfilePaymentRecord.AsNoTracking().FirstOrDefaultAsync(x => x.AttendenceId == id && x.FeeStatus == true);
			var paymentTime = "";
			if (paymentRecord != null)
			{
				paymentTime = conferenceMaster.IsInternational ? paymentRecord.CreateDate.Value.ToString("yyyy-MM-dd HH:mm") : paymentRecord.CreateDate.Value.ToString("MM/dd/yyyy HH:mm");
			}

			model.FullName = personal.FullName;
			model.Affiliation = personal.Affiliation;
			model.Mail = personal.Mail;
			model.Tel = personal.Mobile;
			model.Country = conferenceMaster.IsInternational ?
					DbContext.LocationMaster.AsNoTracking().FirstOrDefault(x => x.ID == personal.Country)?.NameEn :
					DbContext.LocationMaster.AsNoTracking().FirstOrDefault(x => x.ID == personal.Country)?.Name;
			model.Essay = essay;
			model.Address = personal.Address;
			model.ZipCode = personal.ZipCode;
			model.Fee = personal.Currency + ConstValues.strSpace + (isBenefit ? personal.Discount : personal.TotalFee).Value.ToString("N2");
			model.PayType = conferenceMaster.IsInternational ?
					DbContext.SysPaymentMaster.AsNoTracking().FirstOrDefault(x => x.ID == payTypeId)?.PaymentNameEn :
					DbContext.SysPaymentMaster.AsNoTracking().FirstOrDefault(x => x.ID == payTypeId)?.PaymentName;
			model.InvoiceTitle = personal.InvoiceTitle;
			model.InvoiceNum = personal.InvoiceNum;
			model.AddressAndTel = personal.AddressAndTel;
			model.Bank = personal.Bank;
			model.BankAccount = personal.BankAccount;
			model.BankAndAccount = personal.Bank + ConstValues.chrSpace + personal.BankAccount;
			model.TaxNum = personal.TaxNum;
			model.InvoiceId = personal.InvoiceId;
			model.InvoiceDetail = DbContext.ConferenceInvoiceMaster.AsNoTracking().FirstOrDefault(x => x.ID == personal.InvoiceId)?.InvoiceDetail;
			model.HotelName = DbContext.HotelMaster.AsNoTracking().FirstOrDefault(x => x.ID == personal.HotelId)?.HotelName;
			model.RoomType = DbContext.RoomMaster.AsNoTracking().FirstOrDefault(x => x.ID == personal.RoomTypeId)?.RoomType;
			model.ArrivalDate = personal.ArrivalDate.HasValue ? (conferenceMaster.IsInternational ?
					personal.ArrivalDate.Value.ToString("MM/dd/yyyy") :
					personal.ArrivalDate.Value.ToString("yyyy-MM-dd")) : null;
			model.Creator = personal.Creator;
			model.DeparturalDate = personal.DeparturalDate.HasValue ? (conferenceMaster.IsInternational ?
					personal.DeparturalDate.Value.ToString("MM/dd/yyyy") :
					personal.DeparturalDate.Value.ToString("yyyy-MM-dd")) : null;
			model.Id = personal.ID;
			model.ArrivalFlight = personal.ArrivalFlight;
			model.DeparturalFlight = personal.DeparturalFlight;
			model.Remark = string.IsNullOrEmpty(personal.Remark) ? string.Empty : personal.Remark.Replace("\r\n", "\\n");
			model.CreateDate = personal.CreateDate.HasValue ? (conferenceMaster.IsInternational ?
					personal.CreateDate.Value.ToString("MM/dd/yyyy") :
					personal.CreateDate.Value.ToString("yyyy-MM-dd")) : null;
			model.HotelRemark = personal.HotelRemark;
			model.AttendenceIdentity = DbContext.AttendenceIdentityMaster.AsNoTracking().FirstOrDefault(x => x.ID == personal.AttendenceIdentityId)?.IdentityName;
			model.PaymentHasPay = personal.ActuallyFee.HasValue ? (personal.Currency + ConstValues.strSpace + personal.ActuallyFee.Value.ToString("N2")) : string.Empty;
			model.HasPaid = personal.HasPaid == true ? Resources.HasPaid : Resources.HasNotPaid;
			model.FeeDetail = feeDetail;
			model.PaymentTime = paymentTime;
			model.ConferenceName = conferenceMaster.ConferenceName;
			model.AttendId = personal.ID;
			model.ReportId = reportId;
			model.Customize1 = personal.Customize1;
			model.Customize2 = personal.Customize2;
			model.Customize3 = personal.Customize3;
			model.Customize4 = personal.Customize4;
			model.Customize5 = personal.Customize5;
			model.Customize6 = personal.Customize6;
			model.Customize7 = personal.Customize7;
			model.Customize8 = personal.Customize8;
			model.Customize9 = personal.Customize9;
			model.Customize10 = personal.Customize10;
			model.CustomizeList = Utility.GetAttendenceCustomizeList(personal.ConferenceId);

			return View(model);
		}

		[HttpPost]
		[ValidateAntiForgeryToken]
		[ValidateInput(false)]
		[Route("UploadBackground/{ConferenceId}")]
		public async Task<JsonCamelCaseResult> UploadBackground(ConferenceLocaleModel model)
		{
			string controller = RouteData.Values["controller"].ToString();
			string actionName = RouteData.Values["action"].ToString();
			Utility.InsertLog(LoginUser, Request.Url.ToString(), controller, actionName, "PrintView", model.ConferenceId);

			if (model.PicForBackgroundFile != null)
			{
				var result = await DbContext.ConferenceMaster.AsNoTracking()
						.FirstOrDefaultAsync(x => x.ID == model.ConferenceId);

				string nickName = result.ConferenceNickName;
				string folder = Path.Combine(ConstValues.ConferenceImg, nickName);
				string pfolder = Path.Combine(Server.MapPath(ConstValues.ConferenceImg), nickName);
				string fileName = nickName + ConstValues.strHyphen +
						Path.GetExtension(model.PicForBackgroundFile.FileName).Replace(".", "").ToUpper() + ConstValues.strHyphen +
						DateTime.Now.ToString("yyyy") + ConstValues.strHyphen +
						Utility.GetRandom() + Path.GetExtension(model.PicForBackgroundFile.FileName);

				//model.PicForBackgroundPath = Path.Combine(folder, fileName);
				model.PicForBackgroundPath = folder + "/" + fileName;
				var saveFileTask = Task.Run(() =>
				{
					string pFullPath = Path.Combine(pfolder, fileName);
					if (!Directory.Exists(pfolder))
					{
						Directory.CreateDirectory(pfolder);
					}
					model.PicForBackgroundFile.SaveAs(pFullPath);
				});
				Task.WaitAll(saveFileTask);
			}

			return JsonCamelCase(Utility.CreateSuccessJsonResult(Resources.SuccessSubmit, model.PicForBackgroundPath),
					JsonRequestBehavior.AllowGet);
		}

		[HttpPost]
		[ValidateAntiForgeryToken]
		[Route("SavePrintSetting/{ConferenceId}")]
		public async Task<JsonResult> SavePrintSetting(ConferenceLocaleModel model, FormCollection formCollection)
		{
			string controller = RouteData.Values["controller"].ToString();
			string actionName = RouteData.Values["action"].ToString();
			Utility.InsertLog(LoginUser, Request.Url.ToString(), controller, actionName, "PrintView", model.ConferenceId);

			var result = await DbContext.ConferencePrintMaster
					.FirstOrDefaultAsync(x => x.ConferenceId == model.ConferenceId);

			if (result != null)
			{
				result.IsShowName = formCollection.AllKeys.FirstOrDefault(x => x == "IsShowName") == null ? false : true;
				result.NameSize = model.NameSize;
				result.IsNameBold = model.IsNameBold == 1 ? true : false;
				result.IsNameOblique = model.IsNameOblique == 1 ? true : false;
				result.NameLeft = model.NameLeft;
				result.NameTop = model.NameTop;
				result.IsShowAffiliation = formCollection.AllKeys.FirstOrDefault(x => x == "IsShowAffiliation") == null ? false : true;
				result.AffiliationSize = model.AffiliationSize;
				result.IsAffiliationBold = model.IsAffiliationBold == 1 ? true : false;
				result.IsAffiliationOblique = model.IsAffiliationOblique == 1 ? true : false;
				result.AffiliationLeft = model.AffiliationLeft;
				result.AffiliationTop = model.AffiliationTop;
				result.IsShowCountry = formCollection.AllKeys.FirstOrDefault(x => x == "IsShowCountry") == null ? false : true;
				result.CountrySize = model.CountrySize;
				result.IsCountryBold = model.IsCountryBold == 1 ? true : false;
				result.IsCountryOblique = model.IsCountryOblique == 1 ? true : false;
				result.CountryLeft = model.CountryLeft;
				result.CountryTop = model.CountryTop;
				result.IsShowBarCode = formCollection.AllKeys.FirstOrDefault(x => x == "IsShowBarCode") == null ? false : true;
				result.BarCodeSize = model.BarCodeSize;
				result.BarCodeLeft = model.BarCodeLeft;
				result.BarCodeTop = model.BarCodeTop;

				result.IsShowBackground = formCollection.AllKeys.FirstOrDefault(x => x == "IsShowBackground") == null ? false : true;
				result.PicForBackground = model.PicForBackgroundPath;

				result.Updater = LoginUser.UserName;
				result.UpdateIP = LoginUser.IP;
				result.UpdateDate = DateTime.Now;
			}
			else
			{
				var conferencePrintMaster = new ConferencePrintMaster()
				{
					ID = Utility.GetTableId(ConstValues.TableName.ConferencePrintMaster),
					ConferenceId = model.ConferenceId,
					IsShowName = formCollection.AllKeys.FirstOrDefault(x => x == "IsShowName") == null ? false : true,
					NameSize = model.NameSize,
					IsNameBold = model.IsNameBold == 1 ? true : false,
					IsNameOblique = model.IsNameOblique == 1 ? true : false,
					NameLeft = model.NameLeft,
					NameTop = model.NameTop,
					IsShowAffiliation = formCollection.AllKeys.FirstOrDefault(x => x == "IsShowAffiliation") == null ? false : true,
					AffiliationSize = model.AffiliationSize,
					IsAffiliationBold = model.IsAffiliationBold == 1 ? true : false,
					IsAffiliationOblique = model.IsAffiliationOblique == 1 ? true : false,
					AffiliationLeft = model.AffiliationLeft,
					AffiliationTop = model.AffiliationTop,
					IsShowCountry = formCollection.AllKeys.FirstOrDefault(x => x == "IsShowCountry") == null ? false : true,
					CountrySize = model.CountrySize,
					IsCountryBold = model.IsCountryBold == 1 ? true : false,
					IsCountryOblique = model.IsCountryOblique == 1 ? true : false,
					CountryLeft = model.CountryLeft,
					CountryTop = model.CountryTop,
					IsShowBarCode = formCollection.AllKeys.FirstOrDefault(x => x == "IsShowBarCode") == null ? false : true,
					BarCodeSize = model.BarCodeSize,
					BarCodeLeft = model.BarCodeLeft,
					BarCodeTop = model.BarCodeTop,

					IsShowBackground = formCollection.AllKeys.FirstOrDefault(x => x == "IsShowBackground") == null ? false : true,
					PicForBackground = model.PicForBackgroundPath,

					Status = ConstValues.Status.正常,
					Sort = model.Sort.HasValue ? model.Sort.Value : ConstValues.DefaultSort,
					Remark = model.Remark?.Trim(),
					Creator = LoginUser.UserName,
					CreateIP = LoginUser.IP,
					CreateDate = DateTime.Now
				};

				DbContext.ConferencePrintMaster.Add(conferencePrintMaster);
			}

			await DbContext.SaveChangesAsync();

			return JsonCamelCase(Utility.CreateSuccessJsonResult(Resources.SuccessSubmit),
					JsonRequestBehavior.AllowGet);
		}

		[Route("DownloadImportTemplate/{conferenceId}")]
		public ActionResult DownloadImportTemplate(string conferenceId)
		{
			string controller = RouteData.Values["controller"].ToString();
			string actionName = RouteData.Values["action"].ToString();
			Utility.InsertLog(LoginUser, Request.Url.ToString(), controller, actionName, "Index", conferenceId);

			return File(Resources.import_issueInvoice,
					"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
					$"import_issueInvoice.xlsx");
		}

		[HttpPost]
		[ValidateAntiForgeryToken]
		[Route("Import/{ConferenceId}")]
		public async Task<JsonResult> Import(ConferenceLocaleModel model)
		{
			string controller = RouteData.Values["controller"].ToString();
			string actionName = RouteData.Values["action"].ToString();
			Utility.InsertLog(LoginUser, Request.Url.ToString(), controller, actionName, "Index", model.ConferenceId);

			if (model.ImportFile != null && model.ImportFile.InputStream.Length > 0)
			{
				try
				{
					var result = await this.ImportData(model.ConferenceId, model.ImportFile.InputStream);

					if (!string.IsNullOrEmpty(_importMessage))
					{
						return JsonCamelCase(Utility.CreateSuccessJsonResult(_importMessage),
								JsonRequestBehavior.AllowGet, true);
					}
					else
					{
						return JsonCamelCase(Utility.CreateSuccessJsonResult(Resources.SuccessImport),
								JsonRequestBehavior.AllowGet, true);
					}
				}
				catch (Exception)
				{
					return JsonCamelCase(Utility.CreateFailJsonResult(Resources.MsgFileError),
							JsonRequestBehavior.AllowGet, true);
				}
			}
			else
			{
				return JsonCamelCase(Utility.CreateFailJsonResult(Resources.MsgInvalidFile),
					JsonRequestBehavior.AllowGet, true);
			}
		}

		private async Task<int> ImportData(string conferenceId, Stream stream)
		{
			var conferenceInfo = await DbContext.ConferenceMaster.AsNoTracking()
					.FirstOrDefaultAsync(x => x.ID == conferenceId);

			XSSFWorkbook workbook;
			workbook = new XSSFWorkbook(stream);

			ISheet sheet = workbook.GetSheetAt(0);
			int rowIndex = 0;
			int recordCount = 0;
			int errorCount = 0;

			while (true)
			{
				var tmpMsg = string.Empty;
				try
				{
					rowIndex++;
					IRow row = sheet.GetRow(rowIndex);
					if (row == null)
					{
						break;
					}

					var model = new ConferenceLocaleModel()
					{
						ConferenceId = conferenceId
					};
					int columnIndex = 0;

					// 注册号
					model.Id = Utility.ReadExcelField(row.GetCell(columnIndex));

					if (string.IsNullOrEmpty(model.Id))
					{
						continue;
					}

					var result = DbContext.ConferenceAttendenceInfo.FirstOrDefault(x => x.ID == model.Id && x.ConferenceId == conferenceId);
					if (result == null)
					{
						tmpMsg += string.Format("【{0}】的{1}不存在！", model.Id, Resources.AttendenceId) + ConstValues.strHtmlChengeLine;
					}
					else
					{
						// 发票抬头
						columnIndex++;
						if (row.GetCell(columnIndex) != null)
						{
							model.InvoiceTitle = Utility.ReadExcelField(row.GetCell(columnIndex));

							if (string.IsNullOrEmpty(model.InvoiceTitle))
							{
								tmpMsg += string.Format("【{0}】的{1}不存在！", model.Id, Resources.InvoiceTitle) + ConstValues.strHtmlChengeLine;
							}
							if (model.InvoiceTitle.Length > 100)
							{
								tmpMsg += string.Format("【{0}】的{1}长度不得大于{2}！", model.Id, Resources.InvoiceTitle, 100) + ConstValues.strHtmlChengeLine;
							}
							if (result.InvoiceTitle != model.InvoiceTitle)
							{
								tmpMsg += string.Format("【{0}】的{1}的信息导入不成功，请核对！", model.Id, Resources.InvoiceTitle) + ConstValues.strHtmlChengeLine;
							}
						}

						// 发票介质
						columnIndex++;
						if (row.GetCell(columnIndex) != null)
						{
							model.InvoiceType = Utility.ReadExcelField(row.GetCell(columnIndex));

							if (model.InvoiceType.Length > 100)
							{
								tmpMsg += string.Format("【{0}】的{1}长度不得大于{2}！", model.Id, Resources.InvoiceType, 100) + ConstValues.strHtmlChengeLine;
							}
						}

						// 发票类型
						columnIndex++;
						if (row.GetCell(columnIndex) != null)
						{
							model.InvoiceClass = Utility.ReadExcelField(row.GetCell(columnIndex));

							if (model.InvoiceClass.Length > 100)
							{
								tmpMsg += string.Format("【{0}】的{1}长度不得大于{2}！", model.Id, Resources.InvoiceClass, 100) + ConstValues.strHtmlChengeLine;
							}
						}

						// 开票日期
						columnIndex++;
						if (row.GetCell(columnIndex) != null)
						{
							model.InvoiceDate = Utility.ReadExcelField(row.GetCell(columnIndex));

							if (model.InvoiceDate.Length > 100)
							{
								tmpMsg += string.Format("【{0}】的{1}长度不得大于{2}！", model.Id, Resources.InvoiceDate, 100) + ConstValues.strHtmlChengeLine;
							}
						}

						// 发票代码
						columnIndex++;
						if (row.GetCell(columnIndex) != null)
						{
							model.InvoiceCode = Utility.ReadExcelField(row.GetCell(columnIndex));

							if (model.InvoiceCode.Length > 100)
							{
								tmpMsg += string.Format("【{0}】的{1}长度不得大于{2}！", model.Id, Resources.InvoiceCode, 100) + ConstValues.strHtmlChengeLine;
							}
						}

						// 发票号
						columnIndex++;
						if (row.GetCell(columnIndex) != null)
						{
							model.InvoiceNum = Utility.ReadExcelField(row.GetCell(columnIndex));

							if (string.IsNullOrEmpty(model.InvoiceNum))
							{
								tmpMsg += string.Format("【{0}】的{1}不存在！", model.Id, Resources.InvoiceNum) + ConstValues.strHtmlChengeLine;
							}
							if (model.InvoiceNum.Length > 100)
							{
								tmpMsg += string.Format("【{0}】的{1}长度不得大于{2}！", model.Id, Resources.InvoiceNum, 100) + ConstValues.strHtmlChengeLine;
							}
						}

						// 开票金额
						columnIndex++;
						if (row.GetCell(columnIndex) != null)
						{
							model.InvoiceAmountForIpt = Utility.ReadExcelField(row.GetCell(columnIndex));

							float tmp;
							if (!float.TryParse(model.InvoiceAmountForIpt, out tmp))
							{
								tmpMsg += string.Format("【{0}】的{1}的信息导入不成功，请核对！", model.Id, Resources.InvoiceAmount) + ConstValues.strHtmlChengeLine;
							}
						}

						// 收件地址
						columnIndex++;
						if (row.GetCell(columnIndex) != null)
						{
							model.InvoiceAddress = Utility.ReadExcelField(row.GetCell(columnIndex));

							if (model.InvoiceAddress.Length > 200)
							{
								tmpMsg += string.Format("【{0}】的{1}长度不得大于{2}！", model.Id, Resources.InvoiceAddress, 200) + ConstValues.strHtmlChengeLine;
							}
						}

						// 收件人
						columnIndex++;
						if (row.GetCell(columnIndex) != null)
						{
							model.InvoiceReceive = Utility.ReadExcelField(row.GetCell(columnIndex));

							if (model.InvoiceReceive.Length > 100)
							{
								tmpMsg += string.Format("【{0}】的{1}长度不得大于{2}！", model.Id, Resources.InvoiceReceive, 100) + ConstValues.strHtmlChengeLine;
							}
						}

						// 联系电话
						columnIndex++;
						if (row.GetCell(columnIndex) != null)
						{
							model.InvoiceTel = Utility.ReadExcelField(row.GetCell(columnIndex));

							if (model.InvoiceTel.Length > 100)
							{
								tmpMsg += string.Format("【{0}】的{1}长度不得大于{2}！", model.Id, Resources.InvoiceTel, 100) + ConstValues.strHtmlChengeLine;
							}
						}

						// 快递信息
						columnIndex++;
						if (row.GetCell(columnIndex) != null)
						{
							model.InvoiceExpress = Utility.ReadExcelField(row.GetCell(columnIndex));

							if (model.InvoiceExpress.Length > 200)
							{
								tmpMsg += string.Format("【{0}】的{1}长度不得大于{2}！", model.Id, Resources.InvoiceExpress, 200) + ConstValues.strHtmlChengeLine;
							}
						}

						// 邮箱
						columnIndex++;
						if (row.GetCell(columnIndex) != null)
						{
							model.InvoiceMail = Utility.ReadExcelField(row.GetCell(columnIndex));

							if (model.InvoiceMail.Length > 100)
							{
								tmpMsg += string.Format("【{0}】的{1}长度不得大于{2}！", model.Id, Resources.InvoiceMail, 100) + ConstValues.strHtmlChengeLine;
							}
						}
					}

					if (!string.IsNullOrEmpty(tmpMsg))
					{
						_importMessage += tmpMsg;
						errorCount += 1;
						continue;
					}

					result.InvoiceType = model.InvoiceType;
					result.InvoiceClass = model.InvoiceClass;
					result.InvoiceDate = model.InvoiceDate;
					result.InvoiceCode = model.InvoiceCode;
					result.InvoiceNum = model.InvoiceNum;
					if (!string.IsNullOrEmpty(model.InvoiceAmountForIpt))
					{
						result.InvoiceAmount = double.Parse(model.InvoiceAmountForIpt);
					}
					result.InvoiceAddress = model.InvoiceAddress;
					result.InvoiceReceive = model.InvoiceReceive;
					result.InvoiceTel = model.InvoiceTel;
					result.InvoiceExpress = model.InvoiceExpress;
					result.InvoiceMail = model.InvoiceMail;
					result.HasInvoiced = true;

					result.Updater = LoginUser.UserName;
					result.UpdateIP = LoginUser.IP;
					result.UpdateDate = DateTime.Now;

					await DbContext.SaveChangesAsync();

					recordCount++;
				}
				catch (Exception)
				{
					continue;
				}
			}

			if (!string.IsNullOrEmpty(_importMessage))
			{
				var tmpStart = string.Format("{0}条信息导入成功，{1}条信息导入失败，详情如下：" + ConstValues.strHtmlChengeLine, recordCount, errorCount);
				var tmpEnd = "请核对导入表格中的必填项是否填写完整，注册号和发票抬头是否与系统中的信息相匹配。";
				_importMessage = tmpStart +_importMessage + tmpEnd;
			}			

			return await Task.FromResult(recordCount);
		}
	}
}